package com.example.productserver.common;

import com.example.productserver.entity.CyGoods;
import com.example.productserver.model.vo.ProductInfoVO;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
public class LocalCache {

    private Cache<String, CyGoods> localCache = null;

    @PostConstruct
    private void init(){
        localCache = CacheBuilder.newBuilder()
                .initialCapacity(10)  //设置本地缓存容器的初始容量
                .maximumSize(500)  //设置本地缓存的最大容量
                .expireAfterWrite(60, TimeUnit.SECONDS).build(); //设置写缓存后多少秒过期
    }

    public void setLocalCache(String key,CyGoods object){
        localCache.put(key,object);
    }

    /***
     * 返回值 如果不存在返回null
     */
    public CyGoods  getCache(String key){
        return localCache.getIfPresent(key);
    }

    public void remove(String key){
        localCache.invalidate(key);
    }
}
